package com.airplane.auto;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceScreen;
import android.provider.Settings;
import android.util.Log;
import android.view.Window;
import android.widget.LinearLayout;
import android.widget.TimePicker;
import android.widget.Toast;

import com.airplane.auto.util.AlarmUtil;
import com.airplane.auto.util.ConfigCenter;
import com.airplane.auto.util.Constants;
import com.mobclick.android.MobclickAgent;
import com.waps.AdView;
import com.waps.AppConnect;

public class MainActivity extends PreferenceActivity implements OnSharedPreferenceChangeListener {
	
	 private static final String CLOSE_ALL= "cell,bluetooth,wifi";
	 
	 private static final int HELP= 1;
	
	 private Context mContext;
	 	 
	 private Preference beginTimePref;
	 
	 private Preference endTimePref;
	 
	 private Preference helpPref;
	 
	 private Preference more;
	 
	 
	 
	 @Override
	    protected void onCreate(Bundle savedInstanceState) {
		 	this.requestWindowFeature(Window.FEATURE_NO_TITLE);
	        super.onCreate(savedInstanceState);
	       
	        mContext = getApplicationContext();
	        getWindow().setBackgroundDrawableResource(R.drawable.default_bg);
	        getListView().setCacheColorHint(0);
	        
	        //如果配置项为空
	        try{
	        	boolean enable = ConfigCenter.getValue(mContext, Constants.ENABLE_AUTO_CHANGE, false);
		        if(!enable){
		        	ConfigCenter.setValue(mContext, Constants.ENABLE_AUTO_CHANGE, false);
		        	ConfigCenter.setValue(mContext, Constants.OPEN_TIME, "00:00");
		        	ConfigCenter.setValue(mContext, Constants.CLOSE_TIME, "07:00");
		        	ConfigCenter.setValue(mContext, "close_items", CLOSE_ALL);
		        	Settings.System.putString(mContext.getContentResolver(), Settings.System.AIRPLANE_MODE_RADIOS, 
		        			CLOSE_ALL);
		        }
	        }catch(Exception e){
	        	Log.w("MainActivity", "key is exists");
	        }
	        
	        
	        
	        // Load the preferences from an XML resource
	        addPreferencesFromResource(R.xml.preferences);   
	        
	        beginTimePref = this.findPreference(Constants.OPEN_TIME);
	        endTimePref = this.findPreference(Constants.CLOSE_TIME);
	        helpPref = this.findPreference("help");
	        more = this.findPreference("more");
	        
	        String savedOpenTime = ConfigCenter.getValue(mContext, Constants.OPEN_TIME, "00:00");
		    String savedCloseTime = ConfigCenter.getValue(mContext, Constants.CLOSE_TIME, "07:00");
		    beginTimePref.setSummary(savedOpenTime);
		    endTimePref.setSummary(savedCloseTime);
	
	        autoChange();
	        
	        // 连接服务器. 应用启动时调用.
	        AppConnect.getInstance(this);
	        
	        LinearLayout line = new LinearLayout(this);	        
	        new AdView(this,line).DisplayAd(30);//每30秒轮换一次广告，此参数可修改
	        
	        LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(     
	                   LinearLayout.LayoutParams.FILL_PARENT,     
	                   LinearLayout.LayoutParams.WRAP_CONTENT     
	           );     
	        addContentView(line, p);
	       
	    }
	 
	 private void autoChange(){
		 String savedOpenTime = ConfigCenter.getValue(mContext, Constants.OPEN_TIME, "00:00");
	     String savedCloseTime = ConfigCenter.getValue(mContext, Constants.CLOSE_TIME, "07:00");
         if(ConfigCenter.getValue(mContext, Constants.ENABLE_AUTO_CHANGE, false)){
        	AlarmUtil.runAlarm(mContext,savedOpenTime,true);
		    AlarmUtil.runAlarm(mContext,savedCloseTime,false);
         }
	 }
	 
	 
	 @Override
	    protected void onResume() {
	        super.onResume();	       
	        
	        MobclickAgent.onResume(this);
	        // Set up a listener whenever a key changes
	        getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
	        
	        
	 }

	    @Override
	    protected void onPause() {
	        super.onPause();
	        
	        MobclickAgent.onPause(this);
	        // Unregister the listener whenever a key changes
	        getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
	    }
	    
	    protected void onDestroy() {
	        AppConnect.getInstance(this).finalize();
	        super.onDestroy();
	    }
	 
	 
	 public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
	        // Let's do something when my counter preference value changes
	        if (key.equals(Constants.ENABLE_AUTO_CHANGE)) {
	        	
	        	boolean isAuto = sharedPreferences.getBoolean(key, false);
	        	String msg = isAuto?"启用定时开关机!":"关闭定时开关机";
//	        	ConfigCenter.setValue(mContext, Constants.ENABLE_AUTO_CHANGE, isAuto);
	            Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
	            
	            autoChange();
	        }else if(key.equals("close_items")){
	        	 Settings.System.putString(mContext.getContentResolver(), Settings.System.AIRPLANE_MODE_RADIOS, 
	        			 sharedPreferences.getString(key, CLOSE_ALL));
	        }
	 }
	 
	 
	 public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) {
	   if (preference == beginTimePref) {
		   setBeginTime();
	   }else if(preference == endTimePref){
		   setEndTime();
	   }else if(preference == helpPref){
		   showDialog(HELP);
	   }else if(preference == more){
		   AppConnect.getInstance(this).showOffers(this);
	   }
	   return false;
	}
	 
	 
	 private void setBeginTime(){
	   	String savedOpenTime = ConfigCenter.getValue(mContext, Constants.OPEN_TIME, "00:00");
			 new TimePickerDialog(MainActivity.this,
			          new TimePickerDialog.OnTimeSetListener()
			          {                
			            public void onTimeSet(TimePicker view,int hourOfDay,
			                                  int minute)
			            {
			            	String tempTime = formatTime(hourOfDay)+":"+formatTime(minute);
//			            	txtBeginTime.setText(tempTime);
			            	beginTimePref.setSummary(tempTime);
			            	ConfigCenter.setValue(getApplicationContext(), Constants.OPEN_TIME, tempTime);
			            	//保存时间
//			            	ConfigCenter.setValue(mContext, Constants.OPEN_TIME, tempTime);
			            	boolean show = ConfigCenter.getValue(mContext, Constants.ENABLE_AUTO_CHANGE, false);
				            Log.d("MainActivity", show+"");
			            	//启动定时
			            	AlarmUtil.runAlarm(mContext,tempTime,true);			
			            	Toast.makeText(mContext, "设置每日"+tempTime+"自动关机！", Toast.LENGTH_SHORT).show();
			              
			            }          
			          },getHour(savedOpenTime),getMinute(savedOpenTime),true).show();
	   }
	   
	   private void setEndTime(){
	   	String savedCloseTime = ConfigCenter.getValue(mContext, Constants.CLOSE_TIME, "07:00");
			 new TimePickerDialog(MainActivity.this,
			          new TimePickerDialog.OnTimeSetListener()
			          {                
			            public void onTimeSet(TimePicker view,int hourOfDay,
			                                  int minute)
			            {
			            	String tempTime = formatTime(hourOfDay)+":"+formatTime(minute);
//			            	txtEndTime.setText(tempTime);	
			            	endTimePref.setSummary(tempTime);
			            	ConfigCenter.setValue(getApplicationContext(), Constants.CLOSE_TIME, tempTime);
//			            	ConfigCenter.setValue(mContext, Constants.CLOSE_TIME, tempTime);
			            	AlarmUtil.runAlarm(mContext,tempTime,false);
			            	Toast.makeText(mContext, "设置每日"+tempTime+"自动开机！", Toast.LENGTH_SHORT).show();
			            }          
			          },getHour(savedCloseTime),getMinute(savedCloseTime),true).show();
	   }
	   
	   private String formatTime(int value){
	   	if(value<10){
	   		return "0"+value;
	   	}else{
	   		return String.valueOf(value);
	   	}
	   }
	   
	   private int getHour(String planTime){
	   	planTime = planTime.replace(":", ""); 	   
	   	int hour = 0;
	   	if(planTime!=null && planTime.length()>=4){
	   		hour = Integer.valueOf(planTime.substring(0,2));    
	   	}
	   	return hour; 	   
	   }
	   
	   private int getMinute(String planTime){
	   	planTime = planTime.replace(":", ""); 	   
	   	int minute = 0;
	   	if(planTime!=null && planTime.length()>=4){
	   		minute = Integer.valueOf(planTime.substring(2,4));
	   	}    	
	   	return minute; 	   	
	   }
	   
	   @Override
	    protected Dialog onCreateDialog(int id) {    	
	    	
	        switch (id) {
	       
	        case HELP:	        	
	            return new AlertDialog.Builder(MainActivity.this)
//	                .setIcon(R.drawable.alert_dialog_icon)
	                .setTitle("感谢您的使用")
	                .setMessage(R.string.help)
	                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
	                    public void onClick(DialogInterface dialog, int whichButton) {	                    	
	                    	
	                    }
	                })	                
	                .create();	
	        }
	        return null;
	   }
	   
	   
    
}